package com.mzl.lal4cloud.lxw4rf.service.contract.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mzl.lal4cloud.lxw4rf.service.contract.common.ApiUrl;
import com.mzl.lal4cloud.lxw4rf.service.contract.service.DefaultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author J_luo
 */
@Slf4j
@RestController
@RequestMapping("/sign")
public class SignController {

	@Autowired
	private DefaultService defaultService;

	/**
	 * 查询合同列表
	 * @param str
	 * @return
	 */
	@PostMapping("/contractCentersearch")
	public String contractCentersearch(@RequestBody String str){
		String result = defaultService.post(ApiUrl.Contract.CONTRACT_CENTER_SEARCH, str);
		return result;
	}

	/**
	 * 单合同下载
	 * @param str
	 * @return
	 */
	@PostMapping("/downloadFileByOrder")
	public String downloadFileByOrder(@RequestBody String str) {
		String result = defaultService.post(ApiUrl.Contract.CONTRACT_DOWNLOAD_ORDER, str);
		return result;
	}

    /**
     * 单合同下载
     * @param str
     * @return
     */
    @PostMapping("/download-file")
    public String downloadFile(@RequestBody String str) throws Exception {
        String result = defaultService.post(ApiUrl.Contract.CONTRACT_DOWNLOAD_FILE, str);
        return result;
    }

	/**
	 * 合同签署
	 * @param str
	 * @return
	 */
	@PostMapping("/contractsSign")
	public String contractsSign(@RequestBody String str){
		String result = defaultService.post(ApiUrl.Contract.CONTRACT_SIGN, str);
		return result;
	}


	/**
	 * 发送模板合同
	 * @param str
	 * @return
	 */
	@PostMapping("/doTemplateSendSync")
	public Object doTemplateSendSync(@RequestBody String str){

		log.info("调用发送模板合同接口");

		String result = defaultService.post(ApiUrl.Template.TEMPLATE_SEND_SYNC, str);
		if(JSONUtil.isJson(result)){
			Map<String,Object> resultmap = new HashMap<>();
			List resultList = new ArrayList();
			JSONObject jsonObject = JSONUtil.parseObj(result);
			if( null !=jsonObject.get("code") &&  "0".equals(jsonObject.get("code"))){
				resultmap.put("code",0);
				Map<String,List<Map<String,Object>>> map= (Map<String, List<Map<String, Object>>>) jsonObject.get("data");
				List<Map<String, Object>> contracts = map.get("contracts");
				if(null !=contracts && contracts.size() >0){
					contracts.forEach(c->{
						Map<String,Object> mmp = new HashMap<>();
						List<Map<String,Object>> list = (List) c.get("receivers");
						mmp.put("contractId",c.get("contractId"));
						if(null != list && list.size()>0){
							List<Object> collect = list.stream().filter(t -> "PERSON".equals(t.get("userType").toString())).collect(Collectors.toList());
							mmp.put("receivers",collect);
						}
						resultList.add(mmp);
					});
					resultmap.put("contracts",resultList);
				}
				return  JSONUtil.toJsonStr(resultmap);
			}
		}

		return result;
	}




	/**
	 * 回调接口
	 * @return
	 */
	@PostMapping("/message")
	public String pushUrl(@RequestBody Map<String,Object> map){
		Set<Map.Entry<String, Object>> entries = map.entrySet();
		System.out.println(map);
		return "";
	}

	/**
	 * 标签列表查询
	 */
	@GetMapping("/tags-query")
	public String contractTagsQuery(){
		log.info("调用标签列表查询接口");

		String result = defaultService.get(ApiUrl.Template.Tags.TAGS_SEARCH, null);
		return result;
	}

    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath,String catalogue)
            throws Exception {
        File file = new File(catalogue);
        if(file.exists()==false){
            file.mkdirs();
        }
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

}
